package com.hncboy.chatgpt.front.service.impl;
import java.io.Serializable;
import java.util.UUID;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hncboy.chatgpt.front.service.KeyService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;


@Service
public class KeyServiceImpl implements KeyService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @SneakyThrows
    @Override
    public String generateKey(int amount, String alipayAuthCode) throws AlipayPaymentException {
        // 验证支付宝扫码验证是否通过
        if (!alipayAuthCodeIsValid(alipayAuthCode)) {
            throw new AlipayPaymentException();
        }
        // 生成一个唯一的key
        String key = UUID.randomUUID().toString();
        // 将key以及它可以使用的次数存储到Redis中
        KeyInfo keyInfo = new KeyInfo(amount);
        stringRedisTemplate.opsForValue().set(key, objectMapper.writeValueAsString(keyInfo));
        return key;
    }

    public String getKey(String ip, int amount) throws JsonProcessingException {
        // 生成一个唯一的键（例如使用 UUID）
        String key = UUID.randomUUID().toString();
        // 将该键与 IP 地址相关联，以便后续可以找到与该 IP 相关的信息
        String ipKey = ip;
        stringRedisTemplate.opsForValue().set(ipKey, key);
        // 将新的密钥和可用次数存储在 Redis 中
        KeyInfo keyInfo = new KeyInfo(amount);
        stringRedisTemplate.opsForValue().set(key, objectMapper.writeValueAsString(keyInfo));
        return key;
    }


    public Integer getUsageCount(String key) throws JsonProcessingException {
        String value = stringRedisTemplate.opsForValue().get(key);
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(value);
        return jsonNode.get("usageCount").asInt();
    }

    private boolean alipayAuthCodeIsValid(String authCode) {
        // TODO: 实现支付宝扫码验证逻辑，验证通过返回true，否则返回false。
        return true;
    }

    public static class KeyInfo implements Serializable {

        private static final long serialVersionUID = 1L;

        private int usageCount;

        public KeyInfo(int amount) {
            // 根据金额计算可以使用的次数
            this.usageCount = amount / 10;
        }

        public int getUsageCount() {
            return usageCount;
        }

        public int setUsageCount(int i) {
            return usageCount;
        }

        public void decreaseUsageCount() {
            usageCount--;
        }

        public boolean isExpired() {
            return usageCount <= 0;
        }
    }
}